package cn.ixinjiu.libraryMangement.dao.impl;

import cn.ixinjiu.libraryMangement.dao.IBookSortDao;
import cn.ixinjiu.libraryMangement.entity.BookSort;
import cn.ixinjiu.libraryMangement.utils.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by XinChen on 2023-05-22
 *
 * @TODO
 */
public class BookSortDaoImpl implements IBookSortDao {
    @Override
    public List<BookSort> bookSorts() {
        try {
            ResultSet query = JDBCUtil.query("select * from book_sort", null);
            ArrayList<BookSort> bookSorts = new ArrayList<>();
            while (query.next()) {
                int id = query.getInt("id");
                String name = query.getString("name");
                String description = query.getString("description");
                BookSort bookSort = new BookSort(id, name, description);
                bookSorts.add(bookSort);
            }
            return bookSorts;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int count() {
        try {
            ResultSet query = JDBCUtil.query("SELECT COUNT(*) as count FROM `book_sort`", null);
            int count = 0;
            while (query.next()) {
                count = query.getInt("count");

            }
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int bookSortDel(int id) {
        int update = JDBCUtil.update("delete from book_sort where id = ?", new Object[]{id});
        return update;
    }

    @Override
    public int bookSortUpd(BookSort bookSort) {
        int update = JDBCUtil.update("UPDATE book_sort SET name = ?, description = ? WHERE id = ?;",
                new Object[]{bookSort.getName(), bookSort.getDescription(), bookSort.getId()});
        return update;
    }

    @Override
    public int bookSortAdd(BookSort bookSort) {
        int add = JDBCUtil.update("INSERT INTO book_sort values(null, ?, ?)", new Object[]{bookSort.getName(), bookSort.getDescription()});
        return add;
    }

    @Override
    public BookSort getBookSortById(int bid){
        try {
            ResultSet query = JDBCUtil.query("select * from book_sort where id = ?", new Object[]{bid});
            while (query.next()) {
                int id = query.getInt("id");
                String name = query.getString("name");
                String description = query.getString("description");
                BookSort bookSort = new BookSort(id, name, description);
                return bookSort;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
